<div id="sync">
  <h2>Sync <%= type %> <span style="color:#09f;"><%= name %></span></h2>
  <div id="sync-notify">
    <div class="ant-alert ant-alert-success">Sync started, please wait patiently.</div>
  </div>
  <h2>Log</h2>
  <pre style="min-height: 400px;" id="sync-log"></pre>
</div>
<script>
  var $log = $('#sync-log');
  var $notify = $('#sync-notify');
  var timer;
  var type = '<%= type %>';
  var name = '<%= name %>';
  if (type !== 'package') {
    name = type + ':' + name;
  }
  <% if (syncTaskUrl) { %>
  var resourceURL = '<%= syncTaskUrl %>';
  <% } else { %>
  var resourceURL = '/sync/' + name;
  <% } %>
  $(function() {
    var checkLogId = location.hash.match(/logid=(\w+)/);
    var logid = checkLogId ? checkLogId[1] : '';
    if (logid) {
      return getSyncLog(logid);
    }
    $.ajax({
      url: resourceURL + '?sync_upstream=true',
      type: 'PUT',
      dataType: 'json',
      crossDomain: true,
      success: handleSyncSucess,
      error: function (err) {
        var alert = $('<div class="ant-alert ant-alert-error"></div>');
        var message = 'Sync request error. ';
        if (err.status === 404) {
          message += name + ' not exist in official registry.';
        }
        if (err.status === 500) {
          message += 'Please refresh to sync one more time.';
        }
        $notify.html('');
        alert.html(message);
        $notify.append(alert);
      }
    });
  });
  function handleSyncSucess(data) {
    if (data.ok) {
      timer = setInterval(getSyncLog.bind(null, data.logId), 2000);
      location.hash = '#logid=' + data.logId;
      return;
    }
    $notify.html('<div class="ant-alert ant-alert-error">Sync request error.</div>');
  }

  var syncDone = false;
  var hasFail = false;
  function getSyncLog(id) {
    $.ajax({
      url: resourceURL + '/log/' + id,
      type: 'GET',
      crossDomain: true,
      dataType: 'json',
      success: function (data) {
        if (!data.ok) {
          return;
        }
        syncDone = data.syncDone;
        var log = data.log || '';
        if (log.indexOf('Fail: [') >= 0) {
          var failInfo = log.match(/Fail: \[ (.*?) \]/);
          if (failInfo && failInfo[1]) {
            hasFail = true;
          }
        }
        if (syncDone) {
          log += '\nSync ' + name + ' complete!';
          var logLink = data.logUrl ? (' <a href="' + data.logUrl + '" target="_blank">' + data.logUrl + '</a>') : '';
          if (hasFail) {
            log += ' But some packages sync failed, you can refresh to sync again.';
            location.hash = '';
            $notify.html('<div class="ant-alert ant-alert-error">Sync failed.' + logLink + '</div>');
          } else {
            $notify.html('<div class="ant-alert ant-alert-success">Sync success.' + logLink + '</div>');
          }
          clearInterval(timer);
        }
        $log.html(log);
      }
    });
  }
</script>
